package com.edu.ocrdemo.repository;

import com.edu.ocrdemo.common.TaskStatus;
import com.edu.ocrdemo.entity.Task;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author tfan
 * @Description
 * @Date 2024/12/31 17:16
 **/
@Component
public class TaskRepository {
    private final Map<String, Task> tasks = new ConcurrentHashMap<>();
    private final int MAX_SIZE;

    public TaskRepository(@Value("${task.max-count}") int maxTasks) {
        this.MAX_SIZE = maxTasks;
    }


//    public void save(Task task) {
//        tasks.put(task.getTaskId(), task);
//    }

    public synchronized boolean save(Task task) {
        if (tasks.size() >= MAX_SIZE) {
            return false; // 达到最大任务数，拒绝保存
        }
        tasks.put(task.getTaskId(), task);
        return true;
    }

    public Task findById(String taskId) {
        return tasks.get(taskId);
    }

    public synchronized void delete(String taskId) {
        tasks.remove(taskId);
    }

    public synchronized List<Task> getCompletedTasks() {
        return tasks.values().stream()
                .filter(task -> TaskStatus.COMPLETED.equals(task.getStatus()) || TaskStatus.FAILED.equals(task.getStatus()))
                .collect(Collectors.toList());
    }
}
